package com.sinaapp.kltq.weathermanager;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by 丰小兄 on 2015/7/16.
 * Function: 网络连接层
 */
// check network CONNECTION, not access
public class WeatherNetwork {
    public static boolean checkNetwork(Context context) {
        // check if network connected
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
        boolean isConnected = false;
        if (networkInfos != null && networkInfos.length > 0) {
            for (NetworkInfo info : networkInfos) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    isConnected = true;
                }
            }
        }
        return isConnected;
    }
    // if get nothing, return null
    public static String getStringFromURL(URL url, int timeout) {
        HttpURLConnection conn;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(false);
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            if (conn.getResponseCode() != 200) {
                // failed to cunnect
                return null;
            }
            String buffer = new String();
            InputStream is = conn.getInputStream();
            if (is != null) {
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str;
                while ((str = br.readLine()) != null) {
                    buffer = buffer + str;
                }
            }
            return buffer;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
